package ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;

import com.peng.auctionsystem.R;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.util.Calendar;

import base.BaseActivity;

public class CalendarChooseActivity extends BaseActivity {

    private static final String TAG = "CalendarChooseActivity";

    private CalendarDay calendarDay;

    String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {

        MaterialCalendarView materialCalendarView = findViewById(R.id.calendarView);

        materialCalendarView.state().edit()
                .setFirstDayOfWeek(Calendar.SUNDAY)
                .setMinimumDate(CalendarDay.from(2016, 4, 3))
                .setMaximumDate(CalendarDay.from(2100, 5, 12))
                .setCalendarDisplayMode(CalendarMode.MONTHS)
                .commit();

        materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                calendarDay = widget.getSelectedDate();

                Log.d(TAG, "onRangeSelected: " + (calendarDay.getMonth() + 1));
                Log.d(TAG, "onRangeSelected: " + calendarDay.getDay());
                Log.d(TAG, "onDateSelected: " + getDayOfTheWeek(calendarDay));

                Bundle bundle = new Bundle();
                bundle.putString("year",String.valueOf(calendarDay.getYear()));
                bundle.putString("month", String.valueOf((calendarDay.getMonth() + 1)));
                bundle.putString("day", String.valueOf(calendarDay.getDay()));
                bundle.putString("dayOfWeek", getDayOfTheWeek(calendarDay));
                setResult(RESULT_CANCELED, getIntent().putExtras(bundle));
                finish();
            }
        });
    }

    public String getDayOfTheWeek(CalendarDay calendarDay) {
        Calendar calendar = calendarDay.getCalendar();
        int week_index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_calendar_choose;
    }

    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK)
            return true;//不执行父类点击事件
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }
}

